#pragma once

#include <iostream>
#include <poll.h>
#include <sys/time.h>
#include "Socket.hpp"

using namespace std;

static const uint16_t defaultport = 8888; 
static const int fd_num_max = 64;  
int defaultfd = -1;
int non_event = 0;

class PollServer
{
public:
    PollServer(uint16_t port = defaultport):_port(port)
    {
        for(int i = 0; i < fd_num_max; i++)
        {
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = non_event;
            _event_fds[i].revents = non_event;
        }
    }

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        return true;
    }

    void PrintFd()
    {
        cout << "online fd list: ";
        for (int i = 0; i < fd_num_max; i++)
        {
            if(_event_fds[i].fd == defaultfd) continue;
            cout << _event_fds[i].fd <<" ";
        }
        cout << endl;
    }
    void Accepter()
    {
        //连接事件就绪，可以accept了
        string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(clientip,clientport);
        if(sock < 0) return;
        lg(Info, "accept success, %s: %d, sock fd: %d", clientip.c_str(), clientport, sock);

        int i =1;
        for( ; i < fd_num_max; i++)
        {
            if(_event_fds[i].fd != defaultfd) continue;
            else break;
        }
        if(i == fd_num_max)//说明便利整个数组结束，发现没有位置了，直接关闭该套接字fd
        {
            lg(Warning, "server is full, close %d now!", sock);
            close(sock);
        }
        else
        {
            //不能立刻读，要把它写进数组，否则如果读没就绪，会一直阻塞
            _event_fds[i].fd = sock;
            _event_fds[i].events = POLLIN;
            _event_fds[i].revents = non_event;
            PrintFd();
        }

    }

    void Recver(int fd, int pos)
    {
        //读就绪
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if(n < 0)
        {
            lg(Warning, "recv error: fd is : %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 这里本质是从select中移除
        }
        else if(n == 0)
        {
            lg(Info, "client quit, me too, close fd is : %d", fd);
            close(fd);
             _event_fds[pos].fd = defaultfd; //从select移除
        }
        else
        {
            buffer[n] = 0;
            cout << "get a messge: " << buffer << endl;
        }
    }

    void Dispatcher()
    {
        //我们不知道哪个fd唤醒了，所以需要从fd_arry里遍历
        for(int i =0; i < fd_num_max; i++)
        {
            int fd = _event_fds[i].fd;
            if(fd == defaultfd) continue;
            if(_event_fds[i].revents & POLLIN)// 写入唤醒了
            {
                //如果fd==套接字，说明要建立新连接，
                if(fd == _listensock.Sockfd())
                {
                    Accepter();//连接新管理
                }
                //fd != 套接字，说明读的就绪准备了
                else
                {
                    Recver(fd, i);
                }
            }
        }
    }

    void Start()
    {
        int listensock = _listensock.Sockfd();
        _event_fds[0].fd = listensock;//将第一个元素设为套接字fd
        _event_fds[0].events = POLLIN;
        int timeout = 3000; //3s轮巡一次
        while(true)
        {
            //进行poll多路复用
            int n = poll(_event_fds, fd_num_max, timeout);
            switch (n)
            {
            case 0:
                cout << "time out, timeout: " << endl;
                break;
            case -1:
                cerr << "poll error" << endl;
            default://有时间就绪了， todo
                cout << "get a new link..." << endl;
                Dispatcher();
                break;
            }
        }
    }
    


    ~PollServer(){}
private:
    Sock _listensock;
    uint16_t _port;
    struct pollfd _event_fds[fd_num_max]; // 数组, 用户维护的！
};